<?php
/**
 * Класс Controller_Ajax_Cart отвечает за обработку ajax-запросов, связанных с корзиной
 * @author Sayp
 */
class Controller_Ajax_Cart extends Controller_Ajax {
	
	public function actionSwitch() {
		switch ($this->arrRequest[2]) {
			case 'buy' : 
				$this->actionBuy();
				break;
			case 'update':
				$this->actionUpdate();
				break;
			case 'delete':
				$this->actionDelete();
				break;
			case 'recalculate':
				$this->actionRecalculate();
				break;
			default:
				$this->setError(404);
				break;
		}
	}
	
	/**
	 * Покупка товара в корзину
	 */
	private function actionBuy() {
		$productId = Service_Escape::requestDataInt('ID_product', 'POST', 0);
		$sizeId = Service_Escape::requestDataInt('ID_size', 'POST', 0);
		
		$objProduct = new Product($productId);
		if (!$objProduct->id) return $this->makeStandardError('Нет такого товара');
		
		$objSize = new Size();
		$objSize->find('first', array('conditions' => "`ID_size` = '" . $sizeId . "' AND `type` = '" . $objProduct->getField('type') . "'"));
		if (!$objSize->id) return $this->makeStandardError('Нет такого размера');
		
		$arrFields = array(
			'ID_product' => $objProduct->id,
			'ID_size' => $objSize->id
		);
		if (User_Seance::getId()) $arrFields['ID_user'] = User_Seance::getId();
		elseif (!isset($_COOKIE['cart_hash'])) { // Если пользователь не авторизован, то генерируем хэш для корзины
			$hash = md5(rand(1, 10000) . $_SERVER['REMOTE_ADDR'] . rand(1, 1000));
			setcookie('cart_hash', $hash, time() + 9999999, '/');
			$arrFields['cart_hash'] = $hash;
		}
		else $arrFields['cart_hash'] = $_COOKIE['cart_hash'];
		
		$objCart = new Cart();
		$objCart->find('first', array(
				'conditions' => 
					"`cart`.`ID_product`='" . $objProduct->id . "' AND
					`cart`.`ID_size`='" . $objSize->id . "' AND
					`cart`." . (isset($arrFields['ID_user']) ? "`ID_user`='" . $arrFields['ID_user'] . "'" : "`cart_hash`='" . $arrFields['cart_hash'] . "'") . " AND
					`cart`.`is_order` = 0"  
		));
		
		if($objCart->id) $success = $objCart->updateFields(array('amount' => $objCart->getField('amount') + 1));
		else {
			$arrFields['amount'] = 1;
			$objCart->setFields($arrFields);
			$success = $objCart->save();
		}
		
		if (!$success) return $this->makeStandardError('Неизвестная ошибка');
		
		$this->arrReturn = array('result' => 'OK');
	}
	
	/**
	 * Отрисовка корзины
	 */
	private function actionUpdate() {
		echo Cart::getCartContentShort();
		exit();
	}
	
	/**
	 * Удаляем товар из корзины
	 */
	private function actionDelete() {
		$productId = Service_Escape::requestDataInt('ID_product', 'POST', 0);
		$sizeId = Service_Escape::requestDataInt('ID_size', 'POST', 0);
		
		if (!$sizeId || !$productId) return $this->makeStandardError('Переданы не все данные');
		$arrCondition = Cart::getArrCondition();
		if (empty($arrCondition)) return $this->makeStandardError('Корзина пуста');
		
		$objDB = Service_Database::instanse();
		$stmt = "DELETE FROM `cart` WHERE `ID_product` = '" . $productId . "' AND `ID_size` = '" . $sizeId . "' AND " . $arrCondition['field'] . " = '" . $arrCondition['value'] . "' AND `cart`.`is_order` = 0";
		$objDB->query($stmt);
		
		$this->arrReturn = array('result' => 'OK');
	}
	
	/**
	 * Пересчитываем содержимое корзины
	 */
	private function actionRecalculate() {
		if (empty($_POST['products'])) return $this->makeStandardError('Корзина пуста');
		
		$objDB = Service_Database::instanse();
		$arrProducts = $_POST['products'];
		$arrCondition = Cart::getArrCondition();
		foreach ($arrProducts as $arrProduct) {
			
			$objProduct = new Product($arrProduct['ID_product']);
			if (!$objProduct->id) return $this->makeStandardError('Нет такого товара');
			
			$objSize = new Size();
			$objSize->find('first', array('conditions' => "`ID_size` = '" . $arrProduct['ID_size'] . "' AND `type` = '" . $objProduct->getField('type') . "'"));
			if (!$objSize->id) return $this->makeStandardError('Нет такого размера');
			
			$stmt = "SELECT `cart`.`amount` FROM `cart` WHERE `ID_product` = '" . $objProduct->id . "' AND `ID_size` = '" . $objSize->id . "' AND " . $arrCondition['field'] . " = '" . $arrCondition['value'] . "' AND `cart`.`is_order` = 0";
			$nrProductCurrent = $objDB->selectOneValue($stmt);
			
			// Если указали не число или число не больше нуля - удаляем запись из корзины
			if(!is_numeric($arrProduct['nr_product']) || $arrProduct['nr_product'] <= 0) {	
				$stmt ="DELETE FROM `cart` WHERE `ID_product` = '" . $objProduct->id . "' AND `ID_size` = '" . $objSize->id . "' AND " . $arrCondition['field'] . " = '" . $arrCondition['value'] . "' AND `cart`.`is_order` = 0";
				$objDB->query($stmt);
			}
			// Если пользователь уменьшил количество продуктов, то удаляем
			if ($nrProductCurrent > $arrProduct['nr_product']) {
				$stmt = ($nrProductCurrent == 1 ? "DELETE FROM `cart`" : "UPDATE `cart` SET `cart`.`amount` = '" . $arrProduct['nr_product'] . "'" ) . " WHERE `ID_product` = '" . $objProduct->id . "' AND `ID_size` = '" . $objSize->id . "' AND " . $arrCondition['field'] . " = '" . $arrCondition['value'] . "' AND `cart`.`is_order` = 0";
				$objDB->query($stmt);
			}
			// Если пользователь увеличил количество продуктов, то добавляем
			elseif ($nrProductCurrent < $arrProduct['nr_product']) {
				$stmt = "UPDATE `cart` SET `cart`.`amount` = '" . $arrProduct['nr_product'] . "' WHERE `ID_product` = '" . $objProduct->id . "' AND `ID_size` = '" . $objSize->id . "' AND " . $arrCondition['field'] . " = '" . $arrCondition['value'] . "' AND `cart`.`is_order` = 0";
				$objDB->query($stmt);
			}
			
			$this->arrReturn = array('result' => 'OK');
		}
	}
}
